package com.ruitu.mall_98_2.mine;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.AppUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.widget.dialog.CustomAlertDialog;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.mvp.contract.BandingThirdAccountContract;
import com.ruitu.mall_98_2.mvp.model.BandingThirdAccountModel;
import com.ruitu.mall_98_2.mvp.presenter.BandingThirdAccountPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.User;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.android.model.UserInfo;

public class BandingThirdAccountActivity extends MyBaseActivity<BandingThirdAccountPresenter, BandingThirdAccountModel> implements BandingThirdAccountContract.View {

    private TextView tv_weixin_banding_status;
    private TextView tv_qq_banding_status;
    private TextView tv_alipay_banding_status;

    private LinearLayout ll_weixin_banding;
    private LinearLayout ll_qq_banding;
    private LinearLayout ll_alipay_banding;
    private User user;

    private String platformName;

    private String unionid;
    private String name;
    private String imageUrl;
    private String type;
    private CustomAlertDialog customAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_banding_third_account;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("账号绑定");
        tv_weixin_banding_status = findViewById(R.id.tv_weixin_banding_status);
        tv_qq_banding_status = findViewById(R.id.tv_qq_banding_status);
        tv_alipay_banding_status = findViewById(R.id.tv_alipay_banding_status);
        ll_weixin_banding = findViewById(R.id.ll_weixin_banding);
        ll_qq_banding = findViewById(R.id.ll_qq_banding);
        ll_alipay_banding = findViewById(R.id.ll_alipay_banding);
        user = AppHolder.instance().getUser();
        if (TextUtils.isEmpty(user.getWxName())) {
            if (TextUtils.isEmpty(user.getWxId())) {
                tv_weixin_banding_status.setText("未绑定");
            } else {
                tv_weixin_banding_status.setText("已绑定");
            }
        } else {
            tv_weixin_banding_status.setText(user.getWxName());
        }

        if (TextUtils.isEmpty(user.getQqName())) {
            if (TextUtils.isEmpty(user.getQqId())) {
                tv_qq_banding_status.setText("未绑定");
            } else {
                tv_qq_banding_status.setText("已绑定");
            }

        } else {
            tv_qq_banding_status.setText(user.getQqName());
        }

//        if (TextUtils.isEmpty(user.getAlipayId())) {
//            tv_alipay_banding_status.setText("未绑定");
//        } else {
//            tv_alipay_banding_status.setText(user.getAlipayId());
//        }

        setListener();
    }

    private void setListener() {
        ll_weixin_banding.setOnClickListener(this);
        ll_qq_banding.setOnClickListener(this);
        ll_alipay_banding.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (user.getAlipayUserInfo() == null) {
            tv_alipay_banding_status.setText("未绑定");
        } else {
            tv_alipay_banding_status.setText(user.getAlipayUserInfo().getAlipayAccount());
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (ll_weixin_banding == v) {
            type = "1";
            if (TextUtils.isEmpty(this.user.getWxName()) && TextUtils.isEmpty(user.getWxId())) {
                if (AppUtils.isInstallApp("com.tencent.mm")) {
                    platformName = "Wechat";
                    setAuthorize(platformName);
                } else {
                    ToastUtils.showShort("您没有安装微信");
                }
            } else {
                customAlertDialog = new CustomAlertDialog(this, "解除与微信的绑定吗", new CustomAlertDialog.OkOnClickListener() {
                    @Override
                    public void OkOnClick() {
                        setUnBanding();
                    }
                });
                customAlertDialog.show();
            }
        }

        if (ll_qq_banding == v) {
            type = "0";
            if (TextUtils.isEmpty(this.user.getQqName()) && TextUtils.isEmpty(user.getQqId())) {
                if (AppUtils.isInstallApp("com.tencent.mobileqq")) {
                    platformName = "QQ";
                    setAuthorize(platformName);
                } else {
                    ToastUtils.showShort("您没有安装QQ");
                }
            } else {
                customAlertDialog = new CustomAlertDialog(this, "解除与QQ的绑定吗", new CustomAlertDialog.OkOnClickListener() {
                    @Override
                    public void OkOnClick() {
                        setUnBanding();
                    }
                });
                customAlertDialog.show();
            }
        }

        if (ll_alipay_banding == v) {
            Intent intent = new Intent(BandingThirdAccountActivity.this, BandingAlipayActivity.class);
            if (user.getAlipayUserInfo() == null) {
                startActivity(intent);

            } else {
                intent.putExtra("update", "update");
                startActivity(intent);
            }
        }
    }

    private void setUnBanding() {
        showProgress();
        mPresenter.unbindQqOrWx(type, user.getAccountId());
    }

    AuthListener mAuthListener = new AuthListener() {
        @Override
        public void onComplete(Platform platform, int i, BaseResponseInfo data) {

            String toastMsg = null;
            switch (i) {
                case Platform.ACTION_AUTHORIZING:
                    hideProgress();
                    if (data instanceof AccessTokenInfo) {        //授权信息
                        String token = ((AccessTokenInfo) data).getToken();//token
                        long expiration = ((AccessTokenInfo) data).getExpiresIn();//token有效时间，时间戳
                        String refresh_token = ((AccessTokenInfo) data).getRefeshToken();//refresh_token
                        String openid = ((AccessTokenInfo) data).getOpenid();//openid
                        //授权原始数据，开发者可自行处理
                        String originData = data.getOriginData();

                    }
                    handler.sendEmptyMessage(979);
                    break;

                case Platform.ACTION_REMOVE_AUTHORIZING:
                    toastMsg = "删除授权成功";
                    hideProgress();
                    break;
                case Platform.ACTION_USER_INFO:
//                    hideProgress();
                    if (data instanceof UserInfo) {      //第三方个人信息
                        String openid = ((UserInfo) data).getOpenid();  //openid
                        name = ((UserInfo) data).getName();  //昵称
                        imageUrl = ((UserInfo) data).getImageUrl();  //头像url
                        int gender = ((UserInfo) data).getGender();//性别, 1表示男性；2表示女性
                        //个人信息原始数据，开发者可自行处理
                        String originData = data.getOriginData();
                        if (type.equals("0")) {
                            unionid = openid;
                        } else {
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(originData);
                                unionid = (String) jsonObject.get("unionid");
                                if (TextUtils.isEmpty(unionid)) {
                                    unionid = openid;
                                }
                                Logg.i("Unionid :" + unionid);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        showProgress();
                        mPresenter.bindingQqOrWx(unionid, type, AppHolder.instance().getUser().getAccountId(), name);
                    }
                    break;
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            hideProgress();
            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    toastMsg = "授权失败";
                    break;
                case Platform.ACTION_REMOVE_AUTHORIZING:
                    toastMsg = "删除授权失败";
                    break;
                case Platform.ACTION_USER_INFO:
                    toastMsg = "获取个人信息失败";
                    break;
            }
            if (handler != null) {
                Message msg = handler.obtainMessage(1);
                msg.obj = toastMsg + (error != null ? error.getMessage() : "") + "-" + errorCode;
                msg.sendToTarget();
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {

            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    hideProgress();
                    toastMsg = "取消授权";
                    break;
                // TODO: 2017/6/23 删除授权不存在取消
                case Platform.ACTION_REMOVE_AUTHORIZING:
                    hideProgress();
                    break;
                case Platform.ACTION_USER_INFO:
                    toastMsg = "取消获取个人信息";
                    hideProgress();
                    break;
            }
            if (handler != null) {
                Message msg = handler.obtainMessage(1);
                msg.obj = toastMsg;
                msg.sendToTarget();
            }
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 979) {
                JShareInterface.getUserInfo(platformName, mAuthListener);
            }
        }
    };

    //第三方登录传的应用名
    public void setAuthorize(String platform) {
        showProgress();
        if (!JShareInterface.isAuthorize(platform)) {
            JShareInterface.authorize(platform, mAuthListener);
        } else {
            JShareInterface.removeAuthorize(platform, mAuthListener);
        }
    }

    @Override
    public void setBindingSuc() {
        if (type.equals("1")) {
            tv_weixin_banding_status.setText(name);
            AppHolder.instance().getUser().setWxName(name);
        } else if (type.equals("0")) {
            tv_qq_banding_status.setText(name);
            AppHolder.instance().getUser().setQqName(name);
        }
    }

    @Override
    public void setUnbundingSuc() {
        String please_banding = "未绑定";
        if (type.equals("1")) {
            tv_weixin_banding_status.setText(please_banding);
            AppHolder.instance().getUser().setWxName("");
            AppHolder.instance().getUser().setWxId("");
        } else if (type.equals("0")) {
            tv_qq_banding_status.setText(please_banding);
            AppHolder.instance().getUser().setQqName("");
            AppHolder.instance().getUser().setQqId("");
        }
        if (customAlertDialog != null) {
            customAlertDialog.dismiss();
        }
    }

    @Override
    public void setAlipayBindingSuc() {
        tv_alipay_banding_status.setText("");
        AppHolder.instance().getUser().setAlipayId("");
    }
}
